package com.wm.reggie.utils;/**
 * @author zqx
 * @since 2024/3/31
 */

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.Map;

/**
 * @author zqx
 * @since
 */
public class JwtUtils {
    //设置token有效期为1个小时
    private static final int TOKEN_TIME_OUT = 3_600;

    //加密key
    private static final String TOKEM_SECRET ="itcast";

    //生成token
    public static String getToken(Map params){
        long currentTimeMillis = System.currentTimeMillis();
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512,TOKEM_SECRET)
                .setExpiration(new Date(currentTimeMillis + TOKEN_TIME_OUT))
                .addClaims(params)
                .compact();
    }

    //获取token中的chiams的信息
    public static Claims getClaims(String token){
        return Jwts.parser()
                .setSigningKey(TOKEM_SECRET)
                .parseClaimsJws(token).getBody();
    }

    //判断token是否有效
    public static boolean verifyToken(String token){
        if (StringUtils.isEmpty(token)){
            return false;
        }
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey("itcast")
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            return false;
        }
        return true;
    }

}
